package homework.api07_3;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class Server {

    private ServerSocket serverSocket;
    private List<PrintWriter> p = new ArrayList<>();
    public Server(){
        try {
            serverSocket = new ServerSocket(9996);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start(){
        try {
            while (true){
                Socket socket = serverSocket.accept();
                ClientHandler clientHandler = new ClientHandler(socket);
                Thread thread = new Thread(clientHandler);
                thread.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private class ClientHandler implements Runnable{
        private Socket socket;
        private String host;
        private String nickName;
        public ClientHandler(Socket socket){
            this.socket = socket;
            host =socket.getInetAddress().getHostAddress();
        }
        public void run(){
            PrintWriter pw = null;
            try {
                while (true){
                    InputStream is = socket.getInputStream();
                    InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
                    BufferedReader br = new BufferedReader(isr);
                    OutputStream os = socket.getOutputStream();
                    OutputStreamWriter osw = new OutputStreamWriter(os,StandardCharsets.UTF_8);
                    BufferedWriter bw = new BufferedWriter(osw);
                    pw = new PrintWriter(bw,true);
                    nickName = br.readLine();
                    p.add(pw);
                    sendBack("上线了,当前在线人数："+p.size());
                    String line;
                    while ((line=br.readLine())!=null){
                        System.out.println(line);
                        sendBack(line);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    p.remove(pw);
                    sendBack("下线了，当前在线人数："+p.size());
                    socket.close();
                } catch (IOException e) {
                }
            }
        }
        private void sendBack(String line){
            for(PrintWriter p : p){
                p.println(nickName+"["+host+"]:"+line);
            }
        }
    }
    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }
}
